var mongoose =require('mongoose');
var User = require('../models/users-models');

//新增数据
exports.create = function(req,res,next){
    var user = new User(req.body);
    user.save()
    .then(data=>{
        res.json(data);
    })
}

//修改
exports.update = function(req,res,next){
    
      var id = req.params.id; // req.param('id')
      // 现在操作的都是mongoose而不是mongodb
      User.findByIdAndUpdate(id,{$set: req.body}, {new:false} )
      .then(data=>{
          res.json({msg:'数据修改成功',status:200}); // 如果你要返回数据，这个data返回的是你之前修改的那个数据内容
      })
  }

  //删除
exports.remove = function(req,res,next){
    var id = req.params.id;   //此时ud是传过来的值
    id = id.split(',');   //将传递的id值变成数组遍历
    let leng = id.length;
    console.log(id);
    // User.remove({ _id: { $in: id } });
    for(var i=0;i<leng;i++){
        User.findByIdAndRemove(id[i],function(err,doc){
            // if(err){
            //     console.log("数据删除异常"+err);
            //     return;
            // }
            // else{
            //     return res.json({msg:'数据删除成功',status:200})
            // }
        });
    }
    res.send();//解决异步处理导致的批量删除问题
} 

//查找
exports.list = function(req,res,next){
    var page = (req.body.page) ? req.body.page : 1;
    var rows = (req.body.rows) ? req.body.rows : 10;
    rows = parseInt(rows);
    var queryCondition = {};
    var name;
    if( req.body.name && req.body.name.trim().length>0 ){
        name = req.body.name;
        queryCondition = {"name":new RegExp(name,'i')}
    }

    //对查找到的数据进行分页
    User.paginate(queryCondition, { page: page, limit: rows }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;
       res.json(result)
    });
}

//登录验证
exports.login = function(req,res,next){
    let password = req.body.password;
    let name = req.body.user;
    var query = {name:name,password:password}
    User.findOne(query,(err,result) => {
            res.json(result)
    })
}